﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace TLD_Vision.OCR {
    public class TemplateMatcher {
        private String testsetPath;

        public TemplateMatcher(String testsetPath) {
            this.testsetPath = testsetPath;
        }

        /// <summary>
        /// Runs ocr test on a given set of images
        /// </summary>
        /// <param name="src">Input character to be recognised</param>
        /// <param name="resultList">List containing the output result. This is not sorted!</param>
        public void RunTestset(Image src, List<OCRResult> resultList) {
            if (src == null) {
                return;
            }
            // Clone the input or the input box will also be resized.
            Image input = src.Clone();
            System.Drawing.Rectangle r = input.FindCharacterRectangle(2);
            input = input.Crop(r).Resize(50, 50);

            // Regex is used to determine the matched character.
            Regex extensionRegex = new Regex(@"\.(jpe?g|png|bmp)$");
            Regex filenameRegex = new Regex(@"(.+)_(.)$");

            if (System.IO.Directory.Exists(testsetPath)) {
                foreach (String filename in System.IO.Directory.EnumerateFiles(testsetPath)) {
                    if (extensionRegex.IsMatch(filename)) {
                        String fontName = System.IO.Path.GetFileNameWithoutExtension(filename);
                        String ch = " ";
                        Match match = filenameRegex.Match(fontName);

                        if (match.Success) {
                            fontName = match.Groups[1].Value;
                            ch = match.Groups[2].Value;
                        }

                        Image rhs = new TLD_Vision.Image(filename);
                        System.Drawing.Rectangle rect = rhs.FindCharacterRectangle(2);
                        rhs = rhs.Crop(rect).Resize(50, 50);

                        int sum = input.TestBitmaps(rhs);
                        resultList.Add(new OCRResult(fontName, ch, sum));
                    }
                }
            }
        }
    }
}
